// pages/FanInfo/FanInfo.js
const app = getApp();
const API = require('../../common/constant');
const util = require('../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    star: false,
    isComment: false,
    ifReply: false,
    commentContent: '',
    leaveWords: [],
    pageIndex: 1,
    pageCount: 0,
    info: {}
  },
  linkToPage() {
    wx.navigateTo({
      url: '../reply/index?userId=' + this.data.info.userId + '&eventId=' + this.data.info.id,
    })
  },
  goToPerson(e) {
    console.log(e.currentTarget.dataset.id);
    let userId = wx.getStorageSync('userInfo').userId;
    if (e.currentTarget.dataset.id + '' == userId + '') {
      wx.navigateTo({
        url: '../myInformation/myInformation'
      })
    } else {
      wx.navigateTo({
        url: '../FanInfo/PersonInfo/PersonInfo?id=' + e.currentTarget.dataset.id
      })
    }
  },
  /**
   * 获取数据
   */
  getActivityInfo: function (param) {
    let sesssionID = wx.getStorageSync("sessionId");
    if (sesssionID.length == 0) {
      wx.showToast({
        title: '您还没有登录，请登录',
        icon: "none",
        duration: 4000
      });
      wx.navigateTo({
        url: '../loginAndRegister/loginAndRegister'
      });
    } else {
      util.http({
        url: API.URL.EVENT.FIND_EVENTINFODETAILBYID,
        data: {
          id: param
        },
        success: (res) => {
          console.log('获取到的活动详情为：', res.data.bussData);
          if (!res.data.bussData) {
            app.showUserInfo('活动已取消，2s后自动返回', 'none', 2000)
            setTimeout(() => {
              wx.navigateBack({})
            }, 2000)
          }
          var newdata = this.changeInfo(res.data.bussData);
          if (res.data.bussData.sign === 'undefined') {
            res.data.bussData.sign = '该用户暂无签名'
          }
          this.setData({
            info: res.data.bussData,
            leaveWords: [],
            pageIndex: 1,
            pageCount: 0
          });
          this.getLeaveWords();
        },
        fail: (rej) => {
          wx.showToast({
            title: '获取不到活动信息',
            icon: "none",
            duration: 4000
          });
          // console.log(rej);
        }
      });
    }
  },
  changeInfo: function (arr) {
    if (arr.eventType == "chat") {
      arr.activityType = "#解闷聊天#";
      arr.activityColor = '#F4BC11';
    } else if (arr.eventType == "partner") {
      arr.activityType = "#美食搭伙#";
      arr.activityColor = '#FF8023';
    } else if (arr.eventType == 'find') {
      arr.activityType = "#求邂逅#";
      arr.activityColor = '#FE3232';
    }
    arr.eventStartTime = this.changeDate(arr.eventStartTime);
    arr.eventEndTime = this.changeDate(arr.eventEndTime);
    arr.registrationStartTime = this.changeDate(arr.registrationStartTime);
    arr.registrationEndTime = this.changeDate(arr.registrationEndTime);
    this.addSeeCount(arr.id, arr.seeCount);
    return arr;
  },
  changeDate: function (date) {
    let yearMonth = date.split('-');
    let dayTime = yearMonth[2].split(' ');
    let time = dayTime[1].split(':');
    let newdate = parseInt(yearMonth[1]) + "月" + parseInt(dayTime[0]) + "日 " + time[0] + ":" + time[1];
    return newdate;
  },

  /**
   * 增加浏览量
   */
  addSeeCount: function (id, count) {
    util.http({
      url: API.URL.EVENT.SAVE_EVENTSEE,
      data: {
        idEventInfoId: id,
        seeCount: count + 1
      },
      success: (res) => {
        // console.log('浏览数加1');
      }
    });
  },
  /**
  * 报名数加1
  */
  // 确认报名
  confimSign: function (e) {
    var that = this;
    if (this.data.info.registrationStatus === "已报名") {
      wx.showToast({
        title: '你已经报名过了',
        icon: "none",
        duration: 2000
      });
    }
    else if (this.data.info.registrationStatus === "立即报名") {
      if(this.data.status === '已结束'){
        app.showUserInfo('很抱歉，活动已结束', 'none', 1500);
        return
      }
      if (this.data.info.eventStatus != '报名中'){
        app.showUserInfo('很抱歉，已错过报名时间', 'none', 1500);
        return
      }
      wx.showModal({
        title: '立即报名',
        content: '如果被选为饭约对象，你的手机号将显示给对方，同时你也将获得对方手机号。',
        confirmText: '确认报名',
        confirmColor: '#FE3232',
        success: function (res) {
          if (res.confirm) {
            let count = that.data.info.registrationSuccessCount;
            let limitCount = that.data.info.eventNumber;
            let sex = wx.getStorageSync('userInfo').sex;
            let limitSex = that.data.info.registrationSex;
            if (count >= limitCount) {
              app.showUserInfo('对不起 报名人数已满', 'none', 1500);
            } else if (sex != limitSex && limitSex != '不限') {
              app.showUserInfo('对不起 您不符合该活动的性别要求', 'none', 1500);
            } else {
              util.http({
                url: API.URL.REGISTRATION.SAVE_EVENTREGISTRATION,
                data: {
                  idEventInfoId: that.data.info.id
                },
                success: (res) => {
                  // console.log('确认报名');
                  that.getActivityInfo(that.data.info.id)
                },
                fail: (rej) => {
                  wx.showToast({
                    title: '报名失败',
                    icon: "none",
                    duration: 2000
                  });
                  // console.log(rej);
                }
              })
            }
          } else if (res.cancel) {
            // console.log('取消')
          }
        }
      });
    }
    else if (this.data.info.registrationStatus === "查看拼友") {
      // console.log(e);
      var currenId = e.currentTarget.id;
      // console.log(currenId);
      let status = this.data.info.eventStatus === '报名中' ? true : false
      console.log(status);
      wx.navigateTo({
        url: '../findPartners/findPartners?id=' + currenId + '&status=' + status
      })
    }
    // console.log();

  },
  // 收藏
  collected: function (e) {
    if (this.data.info.collectionStatus === '已收藏') {
      var that = this;
      util.http({
        url: API.URL.EVENT.DELETE_EVENTCOLLECTION,
        data: {
          idEventInfoId: that.data.info.id
        },
        success: (res) => {
          wx.showToast({
            title: '已取消收藏',
            icon: 'none',
            duration: 1000
          });
          app.globalData.isNewCollect = true;
          that.getActivityInfo(that.data.info.id);
        },
        fail: (rej) => {
          console.log(rej);
        }
      });
    } else {
      var that = this;
      util.http({
        url: API.URL.EVENT.SAVE_EVENTCOLLECTION,
        data: {
          idEventInfoId: that.data.info.id
        },
        success: (res) => {
          wx.showToast({
            title: '已收藏',
            icon: 'none',
            duration: 1000
          });
          that.getActivityInfo(that.data.info.id);
        },
        fail: (rej) => {
          console.log(rej);
        }
      });
    }

  },
  // 点赞
  stared: function (e) {
    if (this.data.info.likeStatus === '已点赞') {
      var that = this;
      util.http({
        url: API.URL.EVENT.DELETE_EVENTLIKE,
        data: {
          idEventInfoId: that.data.info.id
        },
        success: (res) => {
          wx.showToast({
            title: '已取消点赞',
            icon: 'none',
            duration: 1000
          });
          that.getActivityInfo(that.data.info.id);
        }
      });
    } else {
      var that = this;
      util.http({
        url: API.URL.EVENT.SAVE_EVENTLIKE,
        data: {
          idEventInfoId: that.data.info.id
        },
        success: (res) => {
          wx.showToast({
            title: '已点赞',
            icon: 'none',
            duration: 1000
          });
          that.getActivityInfo(that.data.info.id);
        }
      });
    }
  },
  // 跳转到餐厅页面
  toRestaurant: function () {
    let info = this.data.info;
    wx.navigateTo({
      url: `../restConfirm/restConfirm?title=${info.eventAddress}&distance=${info.distance * 1000}&address='未知'&longitude=${info.longitude}&latitude=${info.latitude}&adcode='未知'`
    });
  },
  // 跳转到个人详情页面
  toPersonInfo: function (e) {
    // console.log(e.currentTarget.id);
    wx.navigateTo({
      url: 'PersonInfo/PersonInfo?id=' + e.currentTarget.id
    });
  },

  getLeaveWords() {
    let that = this;
    util.http({
      url: API.URL.MESSAGE.FIND_EVENTMESSAGEBYPAGE,
      data: {
        id: this.data.info.id,
        pageIndex: this.data.pageIndex,
        pageSize: 4
      },
      success(res) {
        console.log('查询留言成功', res);
        that.setData({
          leaveWords: that.data.leaveWords.concat(res.data.bussData),
          pageCount: res.data.pageCount
        })
      },
      fail(res) {
        console.log('查询留言失败', res);
      }
    })
  },
  bindSarchInput(e) {
    console.log(e.detail.value)
    this.setData({
      commentContent: e.detail.value
    })
  },
  giveComment() {
    if (!this.data.commentContent.trim()) {
      app.showUserInfo('请填写内容', 'none', 1000);
      return;
    }
    let info = this.data.info;
    let that = this;
    util.http({
      url: API.URL.MESSAGE.SAVE_MESSAGEINFO,
      data: {
        idEventInfoId: info.id,
        content: this.data.commentContent,
        parentId: 0
      },
      success(res) {
        console.log('留言成功', res)
        that.setData({
          isComment: false,
          leaveWords: [],
          pageIndex: 1,
          pageCount: 0
        })
        that.getLeaveWords();
      },
      fail(res) {
        console.log('留言失败', res)
      }
    })
  },
  openComment() {
    this.setData({
      isComment: true
    })
  },
  hideDelete() {
    this.setData({
      isComment: false,
      isReply: false
    })
  },
  replyReply(e) {
    console.log(e);
    let dataInfo = e.currentTarget.dataset;
    let that = this;
    console.log('replyReply', e.currentTarget.dataset.contentid, e.currentTarget.dataset.username);
    if (dataInfo.isself) {
      {
        let showMsg = '';
        if(e.currentTarget.dataset.delete === 'y'){
          showMsg = '删除评论'
        }else{
          showMsg = '删除回复'
        }
        wx.showModal({
          title: showMsg,
          content: '是否' + showMsg,
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              that.deleteMessage(e.currentTarget.dataset.contentid);
            }
          }
        })
      }
    } else {
      this.setData({
        replyer: dataInfo.username,
        contentid: dataInfo.contentid,
        isReply: true
      })
    }
  },
  giveReply() {
    if (!this.data.commentContent.trim()) {
      app.showUserInfo('请填写内容', 'none', 1000);
      return;
    }
    let that = this;
    util.http({
      url: API.URL.MESSAGE.SAVE_MESSAGEINFO,
      data: {
        idEventInfoId: this.data.info.id,
        content: this.data.commentContent,
        parentId: this.data.contentid
      },
      success(res) {
        console.log('回复成功', res)
        that.setData({
          isReply: false,
          leaveWords: [],
          pageIndex: 1,
          pageCount: 0
        })
        that.getLeaveWords();
      },
      fail(res) {
        console.log('回复失败', res)
      }
    })
  },
  deleteMessage(e) {
    let that = this;
    util.http({
      url: API.URL.MESSAGE.DELETE_MESSAGEINFO,
      data: {
        replyId: e
      },
      success: (res) => {
        that.setData({
          isReply: false,
          leaveWords: [],
          pageIndex: 1,
          pageCount: 0
        })
        that.getLeaveWords();
        console.log('删除留言成功', res);
      },
      fail: (res) => {
        console.log('删除留言失败', res)
      }
    })
  },
  cleanDefault() {
    console.log('阻止冒泡')
  },
  onLoad: function (options) {
    let status = options.status || false;
    let isIndex = options.isIndex || false;
    this.setData({
      id: options.id,
      status: status,
      isIndex: isIndex
    })
  },
  onShow(){
    this.getActivityInfo(this.data.id);
  },
  onReachBottom() {
    if (this.data.pageCount <= this.data.pageIndex) return
    this.setData({
      pageIndex: this.data.pageIndex + 1
    })
    this.getLeaveWords();
  },
  onUnload(){
    if (this.data.isIndex) {
      wx.switchTab({
        url: '../index/index'
      })
    }
  },
  onShareAppMessage: function (res) {
    let id = this.data.info.id;
    let eventUserId = this.data.info.userId;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '还一个人玩呢？来一起约个饭吧！',
      path: '/pages/loginAndRegister/loginAndRegister?id=' + id + '&eventUserId=' + eventUserId,
      imageUrl: '../../images/shareImg.png',
      success: res => {
        // shareAppMessage: ok,
        // shareTickets 数组，每一项是一个 shareTicket ，对应一个转发对象
        // 需要在页面onLoad()事件中实现接口
        wx.showShareMenu({
          // 要求小程序返回分享目标信息
          withShareTicket: true
        });
      }
    }
  }
})